import { onMounted, onUnmounted, ref } from 'vue';
import { useRoute } from 'vue-router';

type Config = {
	targetClass?: string; // 监听的类名（默认：nut-overflow-hidden）
	excludedPaths?: RegExp[]; // 需要排除的路由路径
	lockScroll?: boolean; // 是否锁定滚动位置
};

export function usePreventSwipeByClass(config?: Config) {
	const route = useRoute();
	const observer = ref<MutationObserver>();
	const isListening = ref(false);
	const startX = ref(0);
	const startY = ref(0);

	// 合并配置
	const mergedConfig = {
		targetClass: 'nut-overflow-hidden',
		excludedPaths: [],
		lockScroll: true,
		...config,
	};

	// 核心事件处理
	const handleTouchStart = (e: TouchEvent) => {
		startX.value = e.touches[0].clientX;
		startY.value = e.touches[0].clientY;
	};

	const handleTouchMove = (e: TouchEvent) => {
		if (!shouldPrevent()) return;

		const deltaX = e.touches[0].clientX - startX.value;
		const deltaY = e.touches[0].clientY - startY.value;

		if (Math.abs(deltaX) > Math.abs(deltaY) && e.cancelable) {
			e.preventDefault();
		}
	};

	// 判断是否应该阻止滑动
	const shouldPrevent = () => {
		const isExcludedPath = mergedConfig.excludedPaths.some((re) => re.test(route.path));
		return document.body.classList.contains(mergedConfig.targetClass) && !isExcludedPath;
	};

	// 锁定滚动位置
	const lockScrollPosition = () => {
		if (!mergedConfig.lockScroll) return;
		/** 解决全屏模式下底部导航 位置偏移的问题 */
		window.scrollTo(1, 0);

		window.scrollTo(0, 0);
		document.documentElement.style.overflow = 'hidden';
	};

	// 动态切换事件监听
	const toggleListeners = (shouldAdd: boolean) => {
		const opts = { passive: false };
		if (shouldAdd && !isListening.value) {
			document.addEventListener('touchstart', handleTouchStart, { passive: true });
			document.addEventListener('touchmove', handleTouchMove, opts);
			isListening.value = true;
			lockScrollPosition();
		} else if (!shouldAdd && isListening.value) {
			document.removeEventListener('touchstart', handleTouchStart);
			document.removeEventListener('touchmove', handleTouchMove);
			isListening.value = false;
			document.documentElement.style.overflow = '';
		}
	};

	// 监测 body 类名变化
	const initObserver = () => {
		observer.value = new MutationObserver(() => {
			toggleListeners(shouldPrevent());
		});

		observer.value.observe(document.body, {
			attributes: true,
			attributeFilter: ['class'],
		});
	};

	// 初始化
	onMounted(() => {
		initObserver();
		toggleListeners(shouldPrevent()); // 立即检查初始状态
	});

	// 清理
	onUnmounted(() => {
		observer.value?.disconnect();
		toggleListeners(false);
	});
}
